package icantalk.voip;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.xiph.speex.SpeexEncoder;

/**
 * Thread used for sending datagrams
 *
 * @author Antonín Brettšnajdr
 */
class sendThread implements Runnable {

    private DatagramSocket socket;
    private SoundIO snd;
    private InetSocketAddress address;
    private SpeexEncoder speexEnc;
    
    private boolean isContinue = true;
    
    public void stopRunning()
    {
    	isContinue = false;
    }

    public sendThread(DatagramSocket socket, SoundIO snd, InetSocketAddress address) {
        this.socket = socket;
        this.snd = snd;
        this.address = address;
    }

    @Override
    public void run() {

        byte[] buf;
        DatagramPacket packet;
        long start = System.currentTimeMillis();
        long timestamp;


        while (isContinue) {
            try {
                buf = new byte[640];
                snd.readSamples(buf, 0, buf.length);

                buf = SoundIO.removeDcOffset(buf);
                buf = encodeWithSPEEX(buf);
                timestamp = System.currentTimeMillis() - start;
                packet = PacketFactory.createPacket(timestamp, buf, address);
                socket.send(packet);
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }

    private byte[] encodeWithSPEEX(byte[] buff) {

        if (speexEnc == null) {
            speexEnc = new SpeexEncoder();
            speexEnc.init(1, 3, 8000, 1);
        }

        speexEnc.processData(buff, 0, buff.length);

        byte[] out = new byte[speexEnc.getProcessedDataByteSize()];
        speexEnc.getProcessedData(out, 0);

        return out;
    }
}
